package com.hltx.controller.common;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hltx.constants.CommonConstant;
import com.hltx.controller.base.BaseController;
import com.hltx.pojo.user.User;
import com.hltx.service.common.CommonManager;
import com.hltx.service.picture.PictureManager;
import com.hltx.service.shopping.ShoppingManager;
import com.hltx.util.DateUtil;
import com.hltx.util.ResultInfo;

/**
 * 工具controller
 * 
 * @author shibeilei
 *
 */
@Controller
@RequestMapping("/common")
public class CommonController extends BaseController {

	@Autowired
	private CommonManager commonManager;

	@Autowired
	private ShoppingManager shoppingManager;

	@Autowired
	private PictureManager pictureManager;

	/**
	 * 生成二维码图片并直接以流的形式输出到页面
	 * 
	 * @param code_url
	 * @param response
	 */
	@RequestMapping("qr_code.img")
	@ResponseBody
	public void getQRCode(String code_url, HttpServletResponse response) {
		try {
			commonManager.encodeQrcode(code_url, response.getOutputStream());
		} catch (IOException e) {
		}
	}

	@ResponseBody
	@RequestMapping(value = "synCookieResult", method = { RequestMethod.POST })
	public Map<String, Object> synCookieResult(HttpServletRequest request, HttpServletResponse response,
			HttpSession session) {
		this.logBefore(logger, "登录时同步cookie数据到数据库");
		Map<String, Object> resultMap = new HashMap<>();
		String cookieValue = null;
		try {
			Cookie cookies[] = request.getCookies();
			if (cookies.length > 0) {
				for (Cookie cookie : cookies) {
					if (cookie.getName().equals(CommonConstant.HLTX_SHOPCART_TICKET)) {
						cookieValue = cookie.getValue();
						getGoodsOrderList(cookieValue, session, request, response);
						resultMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", ""));
						break;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resultMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		this.logAfter(logger);
		return resultMap;
	}

	private void getGoodsOrderList(String cookeV, HttpSession session, HttpServletRequest request,
			HttpServletResponse response) {
		this.logBefore(logger, "处理cookie数据");
		Map<String, Object> maps = new HashMap<>();
		Map<String, Object> resultMap = new HashMap<>();
		int buyNum;
		try {
			User user = (User) session.getAttribute("sessionUser");
			String gos[] = cookeV.trim().split("@");
			for (int i = 0; i < gos.length; i++) {
				String goodsItems[] = gos[i].split(":");
				maps.put("userId", user.getId());
				int goodsId = Integer.parseInt(goodsItems[0].toString().trim());
				String spec = goodsItems[1].toString().trim();
				buyNum = Integer.parseInt(goodsItems[2].toString());
				maps.put("goodsId", goodsId);
				maps.put("spec", spec);
				maps.put("buyNum", buyNum);
				maps.put("createTime", DateUtil.getTime());
				maps.put("updateTime", DateUtil.getTime());
				List<Map<String, Object>> list = shoppingManager.getShoppingByAttr(maps);
				if (list.size() == 0) {
					shoppingManager.addShopCart(maps);
				} else {
					int num = (int) list.get(0).get("num");
					String specs = (String) list.get(0).get("spec");
					int buyNums = buyNum + num;
					updateBuyNum(goodsId, specs, buyNums, session, request, response);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resultMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		this.logAfter(logger);

	}

	@RequestMapping(value = "/updateBuyNum", method = { RequestMethod.POST })
	@ResponseBody
	public void updateBuyNum(int goodsId, String spec, int buyNum, HttpSession session, HttpServletRequest request,
			HttpServletResponse response) {
		this.logBefore(logger, "更新购买数量");
		try {
			User user = (User) session.getAttribute("sessionUser");
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("goodsId", goodsId);
			params.put("spec", spec);
			params.put("userId", user.getId());
			params.put("buyNum", buyNum);
			params.put("updateTime", DateUtil.getTime());
			shoppingManager.updateShopBuyNum(params);
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
		}

		this.logAfter(logger);
	}

	@ResponseBody
	@RequestMapping(value = "getGoodsCount", method = { RequestMethod.POST })
	public Map<String, Object> getGoodsCount(HttpServletResponse response, HttpServletRequest request,
			HttpSession session) {
		this.logBefore(logger, "获取购物车商品数量");
		Map<String, Object> resultMap = new HashMap<>();
		Map<String, Object> params = new HashMap<String, Object>();
		try {
			User user = (User) session.getAttribute("sessionUser");
			int goodsNum = 0;
			if (user != null) {
				int userId = user.getId();
				params.put("user_id", userId);
				Object obj = commonManager.getShoppingCountByUserId(params);
				goodsNum = (obj == null) ? 0 : (Integer) obj;
			} else {
				Cookie cookies[] = request.getCookies();
				if (cookies.length > 0) {
					for (Cookie cookie : cookies) {
						if (cookie.getName().equals(CommonConstant.HLTX_SHOPCART_TICKET)) {
							String cookieValue = cookie.getValue();
							String gos[] = cookieValue.split("@");
							for (int i = 0; i < gos.length; i++) {
								String goodsAmount[] = gos[i].split(":");
								if (goodsAmount.length > 2) {
									// 有规格
									goodsNum += Integer.parseInt(goodsAmount[2].toString());

								} else {
									// 普通商品
									goodsNum += Integer.parseInt(goodsAmount[1].toString().trim());
								}
							}
						}
					}
				}
			}
			resultMap.put("goodsNum", goodsNum);
			resultMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", ""));
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resultMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		this.logAfter(logger);
		return resultMap;
	}

	@RequestMapping(value = "downFile", method = { RequestMethod.GET })
	public void downFile(HttpServletResponse response) {
		try {
			byte[] buffer = pictureManager.downFile();
			if (buffer != null) {
				response.reset();
				response.setContentType("text/html;charset=UTF-8");
				response.addHeader("Content-Disposition", "attachment;filename=" + new String("dmeihui.png".getBytes("utf-8"),"iso8859-1"));
			    OutputStream os = new BufferedOutputStream(response.getOutputStream());
			    response.setContentType("application/octet-stream");
			    os.write(buffer);// 输出文件
			    os.flush();
			    os.close();

			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
